import iRunner from '../config/app.config.js';

class HttpService {
    constructor($http, $q) {
        this.$http = $http;
        this.$q    = $q;
    }

    /* baseUrl */
    baseUrl() {
        return iRunner.config.baseUrl
    }

    /* GET */
    getRequest(baseUrl, headers, search) {
        var deferred = this.$q.defer(),
            search   = search || '';

        this.$http({
            headers: {'access-token': headers},
            method: 'GET',
            url: baseUrl + search
        })
        .success(function(data, status, headers, config) {  
            deferred.resolve(data); 
        })
        .error(function(data, status, headers, config) {  
            deferred.reject(data);
        });

        return deferred.promise;
    }

    /* POST */
    postRequest(baseUrl, params, headers, search) {
        var deferred = this.$q.defer(),
            search   = search || '';
        
        this.$http({
            headers: {'access-token': headers},
            method: 'POST',
            url: baseUrl + search,
            data: params
        })
        .success(function(data, status, headers, config) {  
            deferred.resolve(data); 
        })
        .error(function(data, status, headers, config) {  
            deferred.reject(data);
        });

        return deferred.promise;
    }

    /* upload file */
    postMultipart(baseUrl, params, headers, search) {
        var deferred = this.$q.defer(),
            search   = search || '';

        var fd = new FormData();
        angular.forEach(params, function(val, key) {
            fd.append(key, val);
        });

        this.$http({
            method: 'POST',
            url: baseUrl + search,
            data: fd,
            headers: {'Content-Type': undefined, 'access-token': headers},
            transformRequest: angular.identity
        })
        .success(function(data, status, headers, config) {  
            deferred.resolve(data); 
        })
        .error(function(data, status, headers, config) {  
            deferred.reject(data);
        });

        return deferred.promise;
    }
}

HttpService.$inject = ['$http', '$q'];

export default HttpService;
